# -*- coding: utf-8 -*-
from db_conn import *
import io
import time
from datetime import datetime, timedelta
import traceback
import re
from anatel_utils import *
import os

days=7

def getNameLog(format, days_offset, file_type):
    date_now = datetime.now() - timedelta(days=(int(days_offset)))
    #in_file_name_1 = "" + date_now.strftime("%Y-%m-%d") + "_file1.txt"
    
    log_filename = []
    for ftype in file_type:
        log_filename.append(os.path.abspath("" + date_now.strftime(format) + "*" + ftype))
    
    zipname = "log_" + date_now.strftime(format) + "_" + file_type[0] + ".zip"
    print log_filename
    zipLog(log_filename,zipname)
    
    
    #zfilename = "" + date_now.strftime(format) + file_type + ".zip"
    
def  zipLog(archive_list,zfilename):
    import zipfile
    #inclui logs path
    
    if not os.path.exists(os.path.join(os.path.abspath(''),'logs')):
        os.makedirs(os.path.join(os.path.abspath(''),'logs'))
    
    if not os.path.exists(os.path.join(os.path.abspath(''),'logs') + "/" + zfilename):
        zout = zipfile.ZipFile(os.path.join(os.path.abspath(''),'logs') + "/" + zfilename, "w", zipfile.ZIP_DEFLATED)
        for fname in archive_list:
            import glob
            for fna in glob.glob(fname):
                zout.write(fna)
                os.remove(fna)
        zout.close()
        
        if os.path.getsize(os.path.join(os.path.abspath(''),'logs') + "/" + zfilename)==0:
            os.remove(os.path.join(os.path.abspath(''),'logs') + "/" + zfilename)
            print "Arquivo %s com tamanho 0. Removido!" % (os.path.join(os.path.abspath(''),'logs') + "/" + zfilename)
    else:
        print "Arquivo %s jah existe. Skipped!" % (os.path.join(os.path.abspath(''),'logs') + "/" + zfilename)

if __name__ == '__main__':
    if not len(sys.argv) < 2:
        
        for v in sys.argv:
            if len(v.split("="))>1:
                param = v.split("=")[0].strip()
                valor = v.split("=")[1].strip()
                try:
                    if param.lower().strip().find("days")>-1:
                        days = int(valor)
                        print "days: %s" % (days)
                                                                
                    else:
                        eval('%s=%s' % (param,valor))   
                    #print "Param: %s" % (param)
                    #print "Valor: %s" % (valor)
                except:
                    exceptionType, exceptionValue, exceptionTraceback = sys.exc_info()
                    traceback.print_exception(exceptionType, exceptionValue, exceptionTraceback,
                                      limit=2, file=sys.stdout)      
    start_total = time.time()
    
    '''
    20121009_05-REAL-IMPORT.txt
    20121009_05-ERROS-IMPORT.txt
    2012-10-09_file1.txt
    2012-10-09_file2.txt
    20121009_05-DEBUG-CHANGES.txt
    2012-10-09-double_check.txt
    2012-10-09-export-db-id.txt
    2012-10-09-export-db.txt
    2012-10-09_uniq.txt
'''
    #REGRAS, ZIPAR TODOS MENOS O DIA ANTERIOR
        
    file_types_gen = [
                    [['REAL-IMPORT.txt'],"%Y%m%d"],
                    [['ERROS-IMPORT.txt'],"%Y%m%d"],
                    [['file1.txt','file2.txt'],"%Y-%m-%d"],
                    [['DEBUG-CHANGES.txt'],"%Y%m%d"],
                    [['double_check.txt'],"%Y-%m-%d"],
                    [['export-db-id.txt','export-db.txt'],"%Y-%m-%d"],
                    [['uniq.txt'],"%Y-%m-%d"], 
                    [['DEBUG.txt'],"%Y-%m-%d"],                   
                    [['delete.html','insert.html'],"%Y-%m-%d"],
                    [['gen_files.txt'],"%Y-%m-%d"]
                      ]
    
    for i in range(1,days):
        for x in file_types_gen:
            getNameLog(x[1], i, x[0])
        

    print "(Total Tempo Gasto: %s)" % ((time.time() - start_total))